import { useUserStore } from './../stores/user'
import Request from 'luch-request'

const request = new Request({
  baseURL: 'https://consult-api.itheima.net',
})

request.interceptors.request.use(
  (config) => {
    console.log('请求都过来了')
    // 添加token
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    //拿仓库数据
    const store = useUserStore()
    if (store.user.token && config.header) {
      config.header.Authorization = `Bearer ${store.user.token}`
    }

    return config
  },
  (config) => {
    return Promise.reject(config)
  }
)

request.interceptors.response.use(
  (response) => {
    //去除loading
    uni.hideLoading()
    // 2xx 执行
    console.log('请求成功执行这里')
    //这里500是成功
    if (response.data.code !== 10000) {
      // console.log(response.data.message)
      uni.showToast({
        title: response.data.message,
        icon: 'none',
      })
      return Promise.reject(response.data.message)
    }
    return response.data.data
  },
  (response) => {
    //去除loading
    uni.hideLoading()
    // 非2xx 执行
    // console.log('有问题')
    // 发现401 去登录页
    console.log(response.data)

    if (response.data.code === 401) {
      uni.redirectTo({ url: '/pages/login/index' })
      uni.showToast({
        title: '用户登录超时',
        icon: 'none',
      })
      const store = useUserStore()
      store.clearUser()
    }
    return Promise.reject(response)
  }
)

export { request }
